<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="预约时间" value="appointmentDt" />
          <el-option label="下单时间" value="transactTime" />
        </el-select>
        <el-date-picker
          v-show="dateType==='appointmentDt'"
          v-model="date1"
          type="date"
          :picker-options="pickerOptions"
          unlink-panels
          :clearable="false"
        />
        <el-date-picker
          v-show="dateType!=='appointmentDt'"
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
          <el-option value="remark" label="备注" />
          <el-option value="goodsDesc" label="商品描述" />
          <!-- <el-option value="saleMan" label="销售员" /> -->
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="订单来源:">
        <el-select v-model="query.orderSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select
          v-model="query.csmTypeSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
          @change="csmTypeChange"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用气性质:" prop="subType">
        <el-select v-model="query.subType" clearable placeholder="请选择">
          <el-option
            v-for="item in subTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态:">
        <el-select v-model="query.orderReceivingStatus" clearable>
          <el-option label="未接单" :value="1" />
          <el-option label="已接单" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="orgClear"
        />
      </el-form-item>
      <el-form-item label="配送员:">
        <el-select v-model="query.ownerIdList" filterable multiple collapse-tags clearable>
          <el-option v-for="(item, index) in userList" :key="index" :label="item.userName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="超时状态:">
        <el-select v-model="query.overTimeType" clearable>
          <el-option label="超时预警" :value="1" />
          <el-option label="已超时" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[40102, 1]"
          :loading="$loadingPlugin.fetchData"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="9"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile(0)"
        >导出</el-button>
        <!-- <el-button v-permission="16" type="primary" icon="el-icon-download" @click="exportFile(1)">非脱敏导出</el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <csm-location ref="csmLocation" />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymentMethodMap" :parent-fetch-data="search" />
    <order-images ref="orderImages" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="orderStatusMap"
    />
    <pay-detail ref="payDetail" :payment-method-map="paymentMethodMap" />
    <species-amount ref="speciesAmount" />
    <remark-order ref="remarkOrder" />
    <press-order ref="pressOrder" />
    <back-order ref="backOrder" />
    <back-order-apply ref="backOrderApply" />
    <press-order-report ref="pressOrderReport" />
    <sign-order
      ref="signOrder"
      :transactor-list="transactorList"
      :payment-method-map="paymentMethodMap"
    />
    <transfer-order ref="transferOrder" />
    <back-goods ref="backGoods" :payment-method-map="paymentMethodMap" />
    <receipt-confirm ref="receiptConfirm" :payment-method-map="paymentMethodMap" />
    <flow-info ref="flowInfo" />
    <gather ref="gather" />
  </div>
</template>

<script>
  import {
    querySubTypeMap,
    queryTransactorList,
    csDeliverUserList,
    queryMap,
    queryOrderListExport,
    queryExportDomain,
    queryOrderbillReturnParam,
    batchOrderBatchDetail,
    queryCsmInfo,
    queryWaitDispatch,
    batchUserOrder
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { csmTypeMap, defaultPaymentMethodMap, payStatusObj } from '@/utils/map'
  import CsmLocation from '../../../components/CsmLocation'
  import OrderImages from './OrderImages'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import OrderDetail from './OrderDetails'
  import PayDetail from './PayDetail'
  import SpeciesAmount from './SpeciesAmount'
  import RemarkOrder from './Remark'
  import PressOrder from '../../../components/PressOrderModal'
  import BackOrder from './BackOrder'
  import PressOrderReport from '../../../components/PressOrderReport'
  import SignOrder from './SignOrder'
  import TransferOrder from '../../../components/TransferOrderModal'
  import BackGoods from './BackGoods'
  import ReceiptConfirm from './ReceiptConfirm'
  import FlowInfo from './OrderFlow'
  import BackOrderApply from './BackOrderApply'
  import gather from './gather'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { toRMB } from '@/filters'

  export default {
    components: {
      PressOrderReport,
      CsmLocation,
      OrderImages,
      CsmDetail,
      OrderDetail,
      PayDetail,
      SpeciesAmount,
      RemarkOrder,
      PressOrder,
      BackOrder,
      SignOrder,
      TransferOrder,
      BackGoods,
      ReceiptConfirm,
      FlowInfo,
      BackOrderApply,
      gather
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return moment(time.getTime()).diff(moment(Date.now()), 'days') < 0
          }
        },
        actionColWidth: 80,
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        orderSourceMap: [],
        orderFlagMap: [],
        user_qtype: 'ownerId',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'appointmentDt',
        date: [moment().startOf('day'), moment().endOf('day')],
        date1: parseTime(Date.now(), '{y}-{m}-{d}'),
        orderStatusMap: [],
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        calcTypeList: [],
        searchParams: {},
        subTypeList: [],
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          orderSource: [0],
          orderFlagSource: [0],
          isRemedy: '',
          orderStatusSource: [0],
          csmTypeSource: [0],
          payStatus: '',
          paymentMethodSource: [0],
          reStatus: '',
          overTimeType: '',
          ownerIdList: [],
          orderReceivingStatus: 1,
          subType: ''
        },
        roleTypeList: [],
        userList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          // {
          //   prop: 'imageUrl',
          //   label: '图片',
          //   width: 50,
          //   align: 'center',
          //   render: (h, { row }) => {
          //     if (((row.intSpare6 >> 7) & 0x01) > 0) {
          //       return (
          //       <span
          //         onClick={() => this.showImage(row)}
          //         style='color:green;cursor:pointer;'
          //       >
          //         <i class='el-icon-picture' />
          //       </span>
          //       )
          //     } else {
          //       return ''
          //     }
          //   }
          // },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            fixed: 'left',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
              {row.orderCode}
            </el-link>
          )
          },
          {
            prop: 'appointmentDt',
            label: '预约时间',
            minWidth: 200,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(2, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(2, 2)}></i></span>
            },
            render: (h, { row }) => {
              return (
                <div class={this.getClass(row)}>
                  {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                </div>
              )
            }
          },
          {
            prop: 'overTimeType',
            label: '超时状态',
            width: 100,
            render: (h, { row }) => (
            <span class={row.overTimeType === 1 ? 'yellow' : 'red'} onClick={() => this.showTimeoutDetails(row)}>
              {row.overTimeType === 1 ? '超时预警' : row.overTimeType === 2 ? '已超时' : ''}
            </span>
            )
          },
          {
            prop: 'orderReceivingStatus',
            label: '订单状态',
            render: (h, { row }) => (
            <span>
              {row.orderStatus === 2 ? '未接单' : '已接单'}
            </span>
            )
          },
          {
            prop: 'transactTime',
            label: '下单时间',
            width: 140,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(1, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(1, 2)}></i></span>
            },
            render: (h, { row }) => (
            <span>
              {row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'csmAddress',
            label: '联系地址',
            width: 220,
            render: (h, { row }) => {
              return (
              <span>
                <span class='point-span'>
                  {this.$btnPermission([40102, 9]) && row.lon && row.lat && (
                    <i
                      onClick={() => this.openLocation(row)}
                      class='linkColor el-icon-location'
                      style='cursor: pointer;'
                    />
                  )}
                  {!this.$btnPermission([40101, 9]) && (
                    <i class='el-icon-location' style='color:#126edc;cursor: pointer;' />
                  )}
                </span>
                <span>{row.csmAddress}</span>
              </span>
              )
            }
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'ownerName',
            label: '处理人',
            showOverflowTooltip: true
          },
          {
            prop: 'driverName',
            label: '大车司机',
            showOverflowTooltip: true
          },
          {
            prop: 'escortName',
            label: '押运员',
            showOverflowTooltip: true
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
              {row.csmName}
            </el-link>
          )
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => (
            <span>
              {row.csmType &&
                formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc')}
            </span>
          )
          },
          {
            prop: 'subType',
            label: '用气性质',
            minWidth: 110,
            render: (h, { row }) => (
            <span>
              {row.subType ? formatColumnMap(this.subTypeAllList, 'value', row.subType, 'label') : ''}
            </span>
          )
          },
          {
            prop: 'contactPhone',
            label: '客户电话',
            width: 130,
            render: (h, { row }) => {
              if (row.contactPhone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.contactPhone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'goodsCount',
            label: '商品总数',
            align: 'right'
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },
          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.decimalSpare4 && row.decimalSpare4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'decimalSpare1',
            label: '总远距配送费',
            align: 'right',
            width: 110,
            render: (h, { row }) => (
            <span>{row.decimalSpare1 && row.decimalSpare1.toFixed(2)}</span>
          )
          },
          {
            prop: 'distance',
            label: '配送距离(km)',
            align: 'center',
            width: 110,
            render: (h, { row }) => (
            <span>{row.distance && (row.distance / 1000).toFixed(2)}</span>
          )
          },
          {
            prop: 'decimalSpare2',
            label: '总上楼费',
            align: 'right',
            render: (h, { row }) => (
            <span>{row.decimalSpare2 && row.decimalSpare2.toFixed(2)}</span>
          )
          },
          {
            prop: 'decimalSpare3',
            label: '总服务费',
            align: 'right',
            render: (h, { row }) => (
            <span>{row.decimalSpare3 && row.decimalSpare3.toFixed(2)}</span>
          )
          },
          {
            prop: 'totalFee4',
            label: '优惠金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openSpeciesAmount(row)}>
              {row.totalFee4 && row.totalFee4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'treceivables',
            label: '应收金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.treceivables && row.treceivables.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'taccReceivable',
            label: '实收金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.taccReceivable && row.taccReceivable.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => (
            <span style={payStatusObj[row.payStatus]}>
              {row.payStatus
                ? formatColumnMap(this.payStatusMap, 'value', row.payStatus, 'desc')
                : '未支付'}
            </span>
          )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 80,
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      <el-dropdown-item>
                        {row.orderStatus === 2 && (<el-link
                          v-permission={[40102, 2]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openTransferOrder(row, $index)}
                        >
                          转派
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {(row.orderStatus === 2 || row.orderStatus === 5) && (<el-link
                          v-permission={[40102, 3]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openPressOrder(row, $index)}
                        >
                          催单
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {(row.orderStatus === 2 || row.orderStatus === 5) && !!(this.corpSettingData.sp4 >> 22 & 0x01) && (<el-link
                          v-permission={[40102, 11]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openBackOrder(row, $index)}
                        >
                          退单
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {(row.orderStatus === 2 || row.orderStatus === 5) && (<el-link
                          v-permission={[40102, 4]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openSignOrder(row, $index)}
                        >
                          签单
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-link
                          v-permission={[40102, 6]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openRemark(row)}
                        >
                          备注
                        </el-link>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.orderStatus === 10 && row.reStatus !== 2 && (<el-link
                          v-permission={[40102, 13]}
                          underline={false}
                          size='mini'
                          type='danger'
                          onClick={() => this.openBackGoods(row, $index)}
                        >
                          退货
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.payStatus !== 3 && row.fromPlat === 4 && (row.paymentMethod === 2 || row.paymentMethod === 128) && (<el-link
                          v-permission={[40102, 12]}
                          underline={false}
                          size='mini'
                          onClick={() => this.openGather(row, $index)}
                        >
                          收款
                        </el-link>)}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-link
                          v-permission='10'
                          underline={false}
                          size='mini'
                          onClick={() => this.tryPrint(row)}
                        >
                          打印
                        </el-link>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      'query.orderSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderSource.length === this.orderSourceMap.length) {
          this.query.orderSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderFlagSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderFlagSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderFlagSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderFlagSource.length === this.orderFlagMap.length) {
          this.query.orderFlagSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderStatusSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderStatusSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderStatusSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderStatusSource.length === this.orderStatusMap.length) {
          this.query.orderStatusSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.customerTypeMap.length) {
          this.query.csmTypeSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.paymentMethodSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.paymentMethodSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.paymentMethodSource.splice(val.indexOf(0), 1)
        }
        if (this.query.paymentMethodSource.length === this.paymentMethodMap.length) {
          this.query.paymentMethodSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      const res = await querySubTypeMap({})
      this.subTypeAllList = res.data
      this.subTypeList = this.subTypeAllList
      await Promise.all([
        this.getExportDomain(),
        this.getTreeData(),
        this.getTransactorList(),
        // this.getOwnerList(),
        this.queryOptionsMap()
      ])
      this.qtypeChange('ownerId')
    },
    methods: {
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      sortColumn(sortColumn, sortType) {
        this.query.sortColumn = sortColumn
        this.query.sortType = sortType
        this.search()
      },
      async getUserOrder() {
        this.query.ownerIdList = []
        const params = {
          orgSNNo: this.query.orgSNNo
        }
        const res = await batchUserOrder(params)
        this.userList = res.data
      },
      async csmTypeChange(csmType) {
        this.query.subType = ''
        let list = []
        if (csmType.length === 1 && csmType[0] === 0) {
          list = this.subTypeAllList
        }
        if (csmType.indexOf(1) > -1) {
          const res = await querySubTypeMap({ csmType: 1 })
          list = list.concat(res.data)
        }
        if (csmType.indexOf(2) > -1) {
          const res = await querySubTypeMap({ csmType: 2 })
          list = list.concat(res.data)
        }
        if (csmType.indexOf(32) > -1) {
          const res = await querySubTypeMap({ csmType: 32 })
          list = list.concat(res.data)
        }
        if (csmType.indexOf(8) > -1) {
          const res = await querySubTypeMap({ csmType: 8 })
          list = list.concat(res.data)
        }
        if (csmType.indexOf(16) > -1) {
          const res = await querySubTypeMap({ csmType: 16 })
          list = list.concat(res.data)
        }
        // 去重
        const temp = {}
        const result = []
        list.map((item, index) => {
          if (!temp[item.value]) {
            result.push(item)
            temp[item.value] = true
          }
        })
        this.subTypeList = result
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        if (this.query.orderSource[0] === 0) query.orderSource = []
        // query[this.user_qtype] = this.user_qtype_value
        if (this.query.orderFlagSource[0] === 0) query.orderFlagSource = []
        if (this.query.orderStatusSource[0] === 0) query.orderStatusSource = []
        if (this.query.csmTypeSource[0] === 0) query.csmTypeSource = []
        if (this.query.paymentMethodSource[0] === 0) query.paymentMethodSource = []
        if (this.date && this.date.length === 2) {
          if (this.dateType !== 'appointmentDt') {
            query[this.dateType] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            query[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        if (this.dateType === 'appointmentDt' && this.date1) {
          query.appointmentDt = moment(this.date1).format('YYYY-MM-DD') + ' 00:00:00'
          query.dateTimeSpare1 = moment(this.date1).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const res = await queryWaitDispatch(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.query.ownerIdList = []
        this.getOwnerList()
        // this.getUserOrder()
      },
      orgClear() {
        this.userList = []
        this.query.ownerIdList = []
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6, res7, res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderFlag' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'ReStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.orderStatusMap = res1.data.filter((item) => item.value !== 4 && item.value !== 6 && item.value !== 8) // 订单类型(去掉‘已转派’“已接收”“已出库”)
        this.orderFlagMap = res2.data // 订单类型
        this.customerTypeMap = res3.data // 客户类型
        this.payStatusMap = res4.data // 支付状态
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 1024 || item.value === 2048) // 支付方式
        this.reStatusMap = res6.data // 回执状态
        this.orderSourceMap = res7.data // 订单来源
        this.calcTypeList = res8.data // 收款方式
      },
      // 配送距离数据格式化
      distanceFormat(v, r, i) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      // 获取处理人列表
      async getOwnerList() {
        const orgId = this.currentOrg ? this.currentOrg.orgId : 0
        const orgSNNo = this.currentOrg ? this.currentOrg.orgSNNo : 0
        if (orgId) {
          const res = await csDeliverUserList({
            deliveryOrgId: orgId,
            deliveryOrgSNNo: orgSNNo
          })
          this.userList = res.data
          this.ownerList = res.data
        }
        if (this.user_qtype === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 处理人或下单人选择
      qtypeChange(value) {
        if (value === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 点击催单次数
      async openPressOrderReport(row) {
        await this.$refs.pressOrderReport.open({ billCode: row.orderCode, billType: 1 })
      },
      // 点击图片
      async showImage(row) {
        await this.$refs.orderImages.open(row)
      },
      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 点击订单总额
      async openPayDetail(row) {
        await this.$refs.payDetail.open(row)
      },
      // 点击优惠金额
      async openSpeciesAmount(row) {
        await this.$refs.speciesAmount.open(row)
      },
      // 点击备注
      async openRemark(row) {
        await this.$refs.remarkOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击流转信息
      async openFlow(row) {
        await this.$refs.flowInfo.open(row.orderCode)
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击催单
      async openPressOrder(row) {
        await this.$refs.pressOrder.open({ billCode: row.orderCode, billType: 1 })
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // type 默认退单类型
      isShowChargeBackConfirmDialog(row, type = 'backOrder') {
        const tip = type === 'backOrder' ? '点击退单审核通过后，押金单原路退回，是否继续退单？' : '审核通过后，押金单原路退回，是否继续退货？'
        const confirmButtonText = type === 'backOrder' ? '立即退单' : '立即退货'
        const cancelButtonText = type === 'backOrder' ? '暂不退单' : '暂不退货'
        return new Promise((resolve, reject) => {
          // 是否需要先展示退货退单提示确认弹窗
          if (row.relatedDepositCode) {
            this.$confirm(tip, '提示', {
              confirmButtonText: confirmButtonText,
              cancelButtonText: cancelButtonText,
              type: 'warning'
            }).then(async() => {
              resolve()
            }).catch(() => {
              // this.$message({
              //   type: 'info',
              //   message: '已取消退货'
              // })
            })
          } else {
            resolve()
          }
        })
      },
      // 点击退单
      async openBackOrder(row) {
        await this.isShowChargeBackConfirmDialog(row, 'backOrder')
        const res = await queryOrderbillReturnParam({
          orderCode: row.orderCode,
          ownerId: row.ownerId
        })
        const showCheck = JSON.parse(res.data.showCheck)
        if (showCheck) await this.$refs.backOrderApply.open(res.data)
        else await this.$refs.backOrder.open(res.data)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击签单
      async openSignOrder(row) {
        // invenCallarOrReturnBottleInfo({ orderCode: row.orderCode }).then(res => {
        //   console.log(res)
        await this.$refs.signOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
        // })
      },
      // 点击回执确认
      // async openReceiptConfirm(row) {
      //   await this.$refs.receiptConfirm.open(row)
      //   this.$refs.lbTable.fetch({ currentPage: 1 })
      // },
      // 点击退货
      async openBackGoods(row) {
        await this.isShowChargeBackConfirmDialog(row, 'backGoods')
        await this.$refs.backGoods.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 收款
      async openGather(row) {
        await this.$refs.gather.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile(type) {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          params.tabType = 2
          params.desensitizeFlag = type
          queryOrderListExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7 || row.orderStatus === 3) {
          // 7:已退单 3:退单申请中
          return 'danger-row'
        }
        if (row.orderStatus === 9 || row.orderStatus === 12) {
          // 9:退货申请中 12:已退货
          return 'giveup-row'
        }
        return ''
      },
      async tryPrint(row) {
        const params = {
          orderCode: row.orderCode
        }
        const { status, data } = await batchOrderBatchDetail(params)
        if (status === 200) {
          this.tryPrint1(row, data)
        }
      },
      async tryPrint1(row, resdata) {
        const params = {
          csmCode: row.csmCode
        }
        const { status, data } = await queryCsmInfo(params)
        if (status === 200) {
          row['lastBuyDt'] = data['lastBuyDt'] || ''
          row['score'] = data['score'] || 0
          this.print(row, resdata)
        }
      },
      print(row, resdata) {
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['1']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        row.printDt = parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')
        row.printMoney = `${row.treceivables}(${toRMB(row.treceivables)})`
        if (row.payStatus === 3) {
          row.printMoney = `${row.printMoney} 已支付(${formatColumnMap(
            this.paymentMethodMap,
            'value',
            row.payMethod,
            'desc'
          )})`
        }
        row.csmAddress = row.csmAddress.replace(
          /([\u4E00-\u9FA5]*)([省市])(\s*)([\u4E00-\u9FA5]*)市/g,
          ''
        )
        row.payMethod = ''
        for (var item in this.paymentMethodMap) {
          if ((item & row.paymentMethodMap) > 0) {
            row.payMethod += this.paymentMethodMap[item].desc + ','
          }
        }

        row.payMethod = (row.payMethod || '').replace(/(^,+)|(,+$)/g, '')
        row.csmTypeName =
          formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') || '居民用户'

        let printcmd = {
          cmd: 2,
          title: `正在对订单${row.orderCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }

        // let tmpbl =
        //   row.corpCode == "44011" &&
        //   /^[\d]{1,}20$/.test(row.orderCode) &&
        //   dayjs(row.transactDt).format('YY-MM-DD') == "17-11-26";
        if (!window.jCPrint || !window.jCPrint.ws) {
          this.$message.error('打印未连接')
          return
        }
        if (row.csmType) row.csmType = csmTypeMap[row.csmType] // 处理用户类型
        if (row.paymentMethod) row.paymentMethod = defaultPaymentMethodMap[row.paymentMethod] // 处理结算方式
        if (row.transactTime) row.transactTime = moment(row.transactTime).format('YYYY-MM-DD') // 处理下单时间
        if (row.dateTimeSpare3) row.dateTimeSpare3 = moment(row.dateTimeSpare3).format('YYYY-MM-DD') // 处理派单时间
        if (row.transactTime) row.transactTime = moment(row.transactTime).format('YYYY-MM-DD') // 处理制单时间
        window.jCPrint.process(printcmd, temp, row, resdata)
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      },
      async showTimeoutDetails(row) {
        this.$refs.orderDetail.open(row, 'overTime')
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffeced;
}
/deep/ .el-table tr.giveup-row {
  background: #ffeced;
}
/deep/.red {
  color: #f00 !important;
  cursor: pointer;
}
/deep/.yellow {
  color: #ed912e !important;
  cursor: pointer;
}
</style>
